package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.SetmealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import freemarker.template.Configuration;
import freemarker.template.Template;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author xiaycbstart
 * @create 2019 12 21 9:25
 */
@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    private SetmealDao setmealDao;
    @Autowired
    private JedisPool jedisPool;
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;
    @Value("${out_put_path}")
    private String outPutPath;


    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        setmealDao.addSetmeal(setmeal);
        //如何拿到 检查组的id
        addRelationSetmealAndGroup(setmeal.getId(), checkgroupIds);
        if (setmeal.getImg() != null) {
            jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, setmeal.getImg());
            //当添加套餐后需要重新生成静态页面（套餐列表页面、套餐详情页面）
            generateMobileStaticHtml();
        }
    }

    public void generateMobileStaticHtml() {
        //准备模板文件中所需的数据
        List<Setmeal> setmealList = this.findAll();
        if (setmealList != null && setmealList.size() > 0) {
            //生成套餐列表静态页面
            generateMobileSetmealListHtml(setmealList);
            //生成套餐详情静态页面（多个）
            generateMobileSetmealDetailHtml(setmealList);
        }
    }

    public void generateMobileSetmealDetailHtml(List<Setmeal> setmealList) {
        for (Setmeal setmeal : setmealList) {
            Map dataMap = new HashMap();
            dataMap.put("setmeal", this.findById(setmeal.getId()));
            this.generateHtml("mobile_setmeal_detail.ftl", "setmeal_detail_" + setmeal.getId() + ".html", dataMap);
        }
    }

    //生成套餐列表静态页面
    public void generateMobileSetmealListHtml(List<Setmeal> setmealList) {
        Map dataMap = new HashMap();
        dataMap.put("setmealList", setmealList);
        this.generateHtml("mobile_setmeal.ftl", "m_setmeal.html", dataMap);
    }

    //通用的生成html方法
    public void generateHtml(String templateName, String htmlPageName, Map<String, Object> dataMap) {
        //获取configuration对象
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        Writer out = null;
        try {
            Template template = configuration.getTemplate(templateName);
            //静态页面的文件名
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(outPutPath+"/"+htmlPageName)),"utf-8"));
            template.process(dataMap,out);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
      /*  Configuration configuration = freeMarkerConfigurer.getConfiguration();
        Writer out = null;
        try {
            Template template = configuration.getTemplate(templateName);
            //outPutPath + "/" + htmlPageName,
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(outPutPath + "/" + htmlPageName)),"UTF-8"));
            template.process(dataMap, out);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }*/
    }

    @Override
    public void addRelationSetmealAndGroup(Integer setmeal_id, Integer[] checkgroupIds) {
        //如何拿到 检查组的id
        if (checkgroupIds != null && checkgroupIds.length > 0) {
            for (Integer checkgroupId : checkgroupIds) {
                Map<String, Integer> map = new HashMap<>();
                map.put("setmeal_id", setmeal_id);
                map.put("checkgroup_id", checkgroupId);
                setmealDao.addRelation(map);
            }
        }
    }

    @Override
    public List<Setmeal> findAll() {
        return setmealDao.findAll();
    }

    /**
     * @param id
     * @return com.itheima.pojo.Setmeal
     * @author xiayc
     */
    @Override
    public Setmeal findById(Integer id) {
        //此时查找数据库中没有检查组这一项
        Setmeal setmeal = setmealDao.findById(id);
        return setmeal;
    }

    @Override
    public List<Map> findSetmealCount() {
        return setmealDao.findSetmealCount();
    }

    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        Page<Setmeal> page = setmealDao.pageQuery(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(), page.getResult());
    }
}
